/* eslint-disable no-useless-catch */
// /* eslint-disable no-useless-catch */
import { Dialog, Divider, Drawer, Form, Input, Tag } from '@alifd/next';
import { observable, toJS } from 'mobx';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import FormStep from './FormStep';
import FormFooter from './FormFooter';
import BaseInfo from './BaseInfo';
import { t } from '@lingui/macro';
import { Calculate, FormData } from './stores/OrderChangeStore';
import { useStore } from '@/hooks';
import CarrierInfo from './CarrierInfo';
import { DATETIME_TEXT, ENUMS, MAGIC_NUMBERS } from './stores/definitions';
import ChangeConfirm from './ChangeConfirm';

const ChangeOrderDrawer = (props) => {
  const { visible, onClose, order } = props;
  const [form, setForm] = useState(() => observable({}));
  const { ORDER_STATE } = MAGIC_NUMBERS;
  const [calculate, setCalculate] = useState({});
  const { orderChangeStore: store } = useStore();
  const [currStep, setCurrStep] = useState(0);
  const [modal, setModal] = useState([]);
  const editCtx = useRef({ origin: {}, changed: {} }).current;

  useEffect(() => {
    (async () => {
      if (visible) {
        await initData();
      }
    })();
    return (() => {
      store.changedPrice = 0;
    });
  }, [visible]);

  // 是否可修改
  const isPreview = order?.ccOrder?.orderStatus === ORDER_STATE.FINISH;

  // 页面数据初始化
  const initData = async () => {
    const ccOrder = order?.ccOrder || {};
    const merchantId = order?.merchant;
    store.baseRoadPrice = ccOrder?.rootPrice;
    store.changedPrice = order?.price + Number(ccOrder?.priceDifference || 0);
    const task = await store.getTask(order);
    // 承运商附加费
    const initSurchargeInfos = await store.initSurchargeInfos(order, task);

    // 商户附加费
    let initMerchantSurchargeInfos = [];
    if (merchantId) {
      initMerchantSurchargeInfos = await store.initMerchantSurchargeInfos(order, task, merchantId);
    }
    const createFormParam = {
      order,
      task,
      initSurchargeInfos,
      initMerchantSurchargeInfos,
      isPreview,
    };
    const initFormData = new FormData(createFormParam);
    editCtx.origin = _.cloneDeep(initFormData.formData);
    setForm(initFormData);
    setCurrStep(0);

    // 初始化获取分账方参数
    const initCalculate = new Calculate(order, toJS(store.apiRes.transferLinePrice));
    setCalculate(initCalculate);
  };


  // 获取承运信息
  const getRideFormPage = () => {
    const { directRoute } = order?.ccOrder || {};
    const { taskInfo = [] } = toJS(form.formData) || {};
    let res = [
      {
        title: '承运信息',
        content: (
          <CarrierInfo
            key={`${order?.id}-direct`}
            step={currStep}
            isPreview={isPreview}
            form={form}
            order={order}
            calculate={calculate}
            task={taskInfo[0]}
            type="direct"
            index={0}
            onChange={handleChange}
          />),
        stepFunc: directStepTwoToStepThree,
      },
    ];
    if (!directRoute) {
      res = [
        {
          title: 'A段承运信息',
          content: (
            <CarrierInfo
              key={`${order?.id}-from`}
              step={currStep}
              form={form}
              calculate={calculate}
              order={order}
              task={taskInfo[0]}
              type="from"
              onChange={handleChange}
              index={0}
            />
          ),
          stepFunc: transferStepTwoToStepThree,
        },
        {
          title: 'B段承运信息',
          content: (
            <CarrierInfo
              key={`${order?.id}-to`}
              step={currStep}
              form={form}
              order={order}
              task={taskInfo[1]}
              type="to"
              onChange={handleChange}
              calculate={calculate}
              index={1}
              isPreview={isPreview}
            />
          ),
          stepFunc: transferStepThreeToStepFour,
        },
      ];
    }
    return res;
  };

  // 清除所有数据
  const clearData = () => {
    setForm({});
    editCtx.changed = {};
    editCtx.origin = {};
    store.baseRoadPrice = 0;
    store.changedPrice = 0;
  };


  // 取消关闭事件
  const handleCancel = () => {
    // eslint-disable-next-line no-param-reassign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => { v !== undefined && (r[k] = v); }))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => {
          clearData();
          onClose?.();
        },
      });
      return;
    }
    clearData();
    onClose?.();
  };

  const formPage = [
    {
      title: '基本信息',
      content: (
        <>
          <BaseInfo
            isPreview={isPreview}
            form={form}
            order={order}
            calculate={calculate}
          />
        </>
      ),
      stepFunc: stepOneToStepTwo,
    },
    ...getRideFormPage(),
    {
      title: '变更确认',
      content: (
        <ChangeConfirm
          isPreview={isPreview}
          step={currStep}
          form={form}
          order={order}
          editCtx={editCtx}
        />),
    },
  ];

  // 提交
  const handleSubmit = async () => {
    const formData = _.cloneDeep(toJS(form.formData));
    _.assign(formData, {
      basePrice: toJS(store?.apiRes?.baseRoadPrice),
    });
    const originData = toJS(editCtx.origin);
    const param = await form.getParam(originData, formData);
    const args = { subOrders: toJS(form.shareBillInfo) };
    const _data = toJS(param);
    for (let i = 0; i < _data.length; i++) {
      _data[i].otherInfo.dispatchOrderRemarks = toJS(store.dispatchOrderRemarks);
    }
    store.loading = true;
    try {
      await store.updateOrderChange(toJS(param), args);
      setModal([]);
      onClose?.(true);
    } catch (error) {
      Dialog.error({
        content: t`${error}`,
      });
    } finally {
      store.loading = false;
    }
  };

  // 打开订单变更原因弹窗
  const openChangeReasonDialog = () => {
    setModal(['changeReason']);
  };

  // 监听表单改变值
  async function handleChange(values, item) {
    try {
      const { name, value } = item;
      let fieldValue = value;
      if (['beginArea', 'endArea'].includes(name)) {
        // 若区域发生改变，清空地址详情
        const regex = /()Area$/;
        const key = name.replace(regex, '$1');
        _.set(form.formData, `${key}Name`, undefined);
        _.set(form.formData, `${key}Tude`, undefined);
      } else if (['beginName', 'endName'].includes(name)) {
        const regex = /()Name$/;
        const key = name.replace(regex, '$1');
        const [coord, detailName] = value.split('-');
        fieldValue = detailName;
        _.set(form.formData, `${key}Tude`, coord);
      } else if (name === 'predictBeginDate') {
        fieldValue = DATETIME_TEXT(value);
      } else if (name === 'priceDifference') {
        const { ORDER: originOrder } = toJS(values);
        const curPriceDifference = Number(fieldValue);
        const discountPrice = store.countTotalDiscount(originOrder?.discountInfos);
        store.priceDifference = curPriceDifference;
        const originOrderPrice = originOrder.price;
        store.changedPrice = Number(originOrderPrice + curPriceDifference - discountPrice);
      }

      if (!['companyId'].includes(name)) {
        _.set(form.formData, name, fieldValue);
        editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
      }
    } catch (error) {
      Dialog.error({
        content: t`${error}`,
      });
    }
  }

  // 第一步到第二步方法
  async function stepOneToStepTwo() {
    const curFormData = toJS(form.formData);

    try {
      if (!curFormData.beginName || !curFormData.endName) {
        throw (t`请补全详情地址`);
      }
      if (order?.price < toJS(store.changedPrice)) {
        Dialog.warning({ content: t`当前价格大于原价格` });
      }
      // 获取可跑公司数据
      await store.getCompanies(curFormData);
    } catch (error) {
      throw (error);
    }
  }

  // 【直达】第二步到第三步方法
  async function directStepTwoToStepThree() {
    const curFormData = toJS(form.formData);
    if (order?.price < toJS(store.changedPrice)) {
      Dialog.warning({ content: t`当前价格大于原价格` });
    }
    const curPriceDifference = parseFloat((store.changedPrice - order?.price).toFixed(10));
    store.priceDifference = curPriceDifference;
    _.assign(form.formData, { priceDifference: curPriceDifference });
    await checkCalculateAble(0);
  }

  // 【换乘】第二步到第三步方法
  async function transferStepTwoToStepThree() {
    const curFormData = form.formData;
    if (order?.price < toJS(store.changedPrice)) {
      Dialog.warning({ content: t`当前价格大于原价格` });
    }
    const curPriceDifference = parseFloat((store.changedPrice - order?.price).toFixed(10));
    store.priceDifference = curPriceDifference;
    _.assign(form.formData, { priceDifference: curPriceDifference });
    await checkCalculateAble(0);
  }

  // 【换乘】第三步到第四步方法
  async function transferStepThreeToStepFour() {
    const curFormData = form.formData;
    if (order?.price < toJS(store.changedPrice)) {
      Dialog.warning({ content: t`当前价格大于原价格` });
    }
    const curPriceDifference = parseFloat((store.changedPrice - order?.price).toFixed(10));
    store.priceDifference = curPriceDifference;
    _.assign(form.formData, { priceDifference: curPriceDifference });
    await checkCalculateAble(1);
  }

  /**
   * @desc
   * @param {}
   * @return {}
   */
  async function checkCalculateAble(index) {
    const { SPLIT_STATUS } = MAGIC_NUMBERS;
    const { type, errorMsg, subOrder } = await calculate.search();
    switch (type) {
      case SPLIT_STATUS.NEED_REMARK:
        form.shareBillInfo[index] = _.cloneDeep(subOrder);
        throw ({ type: 'warning', message: t`${errorMsg}` });
      case SPLIT_STATUS.NO_SUBMIT:
        form.shareBillInfo[index] = _.cloneDeep(subOrder);
        // form.shareBillInfo = [];
        throw (t`${errorMsg}`);
      default:
        form.shareBillInfo[index] = _.cloneDeep(subOrder);
    }
  }

  return (
    <Drawer
      title={<Title order={order} />}
      visible={visible}
      onClose={handleCancel}
      closeMode={['esc', 'close', 'mask']}
      style={{ maxWidth: '90%' }}
      width="90%"
    >
      <FormStep items={formPage} current={currStep} />
      <Form
        inline
        isPreview={isPreview}
        value={form?.formData}
        onChange={handleChange}
      >
        {formPage[currStep].content}
        <ReasonDialog
          visible={modal[0] === 'changeReason'}
          onClose={() => setModal([])}
          onOk={handleSubmit}
        />
      </Form>
      <FormFooter
        current={currStep}
        handleSetCurrent={setCurrStep}
        onCancel={handleCancel}
        stepFunc={formPage[currStep].stepFunc}
        totalStep={formPage.length}
        onSubmit={openChangeReasonDialog}
      />
    </Drawer>
  );
};

const Title = observer((props) => {
  const { order } = props;
  const { ORDER_STATE } = MAGIC_NUMBERS;
  const { orderStatus } = order?.ccOrder || {};
  const { orderChangeStore: store } = useStore();
  const tabColor = {
    [ORDER_STATE.CANCEL]: 'red',
    [ORDER_STATE.PAID]: 'yellow',
    [ORDER_STATE.START]: 'green',
    [ORDER_STATE.FINISH]: 'orange',
  };
  const discountTotal = store.countTotalDiscount(order?.discountInfos);
  return (
    <>
      <span>订单变更{order?.id}</span>
      <Divider direction="ver" />
      <Tag type="normal" color={tabColor[orderStatus]} >{ENUMS.orderStatus[orderStatus]}</Tag>
      <Divider direction="ver" />
      <span>实付价:{order?.price}</span>
      <Divider direction="ver" />
      <span>变更价格:{toJS(store.changedPrice)}</span>
      <Divider direction="ver" />
      <span>线路基础价:{store.baseRoadPrice}</span>
      <Divider direction="ver" />
      <span>优惠价格:{discountTotal}</span>
    </>
  );
});

const ReasonDialog = observer((props) => {
  const { visible, onClose, onOk } = props;
  const { orderChangeStore: store } = useStore();
  return (
    <>
      <Dialog
        v2
        title={t`订单变更原因`}
        visible={visible}
        onClose={onClose}
        onOk={onOk}
        okProps={{
          loading: store.loading,
          disabled: store.loading,
        }}
      >
        <Form.Item name="orderChangeRemarks">
          <Input.TextArea
            placeholder={t`请输入订单变更原因`}
          />
        </Form.Item>
      </Dialog >
    </>
  );
});

export default observer(ChangeOrderDrawer);
